import random

from flask import render_template, request, session, jsonify, make_response, current_app, g

from app import db
from app.models.models import User
from . import login_blu
# from app.utils.sms.sms.aliyun_sms import send_sms
from app.utils.common.common import login_user_data


@login_blu.route("/login")
def login():
    return render_template("index/login.html")


@login_blu.route("/reg", methods=['POST', "GET"])
def reg():
    if request.method == "GET":
        return render_template("index/register.html")

    elif request.method == "POST":
        # 因为在注册passport_blu蓝图时，添加了url_prefix，所以，浏览器访问次视图函数的方式是：http://localhot:5000/passport/register

        # 获取参数
        # image_code: "123123"
        # mobile: "123123"
        # password: "123123"
        # image_code = request.form.get("image_code")
        # mobile = request.form.get("mobile")
        # password = request.form.get("password")

        # 测试获取前端提交的数据，因为前端已经是json格式提交，所以在使用request.form的时候没有任何数据
        # 在工作中，作为后端的你 一定要和前端及时沟通，否则 容易出现错位，到时影响开发进度（被扣工资）
        print("\n\n\n")
        print("-----------")
        print(request.form)
        print("-----------")
        print(request.json)
        print("-----------")
        print("\n\n\n")

        # 获取用户在注册时提交的数据
        name = request.form.get("name")
        mobile = request.form.get("mobile")
        password = request.form.get("password")
        verify = request.form.get("verify")
        print(name)
        # 进行图片验证码的对比

        # print("image_code", image_code)
        print("session", session.get("captcha"))

        if verify.lower() != session.get("captcha").lower():
            ret = {
                "errno": 1001,  # 为什么这里不用1、2、3....而是使用1001呢？我们在一个项目的开发中可能会出现N个错误，
                # 所以此时我将1开始的即1xxx表示 是注册时的相关错误码，同理 可以在完善登录时 可以使用 2xxxx开始，容易分类
                "errmsg": "验证码错误"
            }
            return jsonify(ret)

        else:
            user = User()
            user.mobile = mobile
            user.nick_name = name
            user.password_hash = password
            try:
                db.session.add(user)
                db.session.commit()
                # 将用户刚刚注册成功的信息，部分保存到session，目的是：标记其登录成功
                ret = {
                    "errno": 0,
                    "errmsg": "注册成功"
                }
            except Exception as ret:
                db.session.rollback()  # 如果在将用户的信息保存到数据库时产生了异常，那么就回滚（如果忘记请查询ACID）
                ret = {
                    "errno": 2,
                    "errmsg": "由于网络因素，注册失败"
                }
            return jsonify(ret)



@login_blu.route("/用户注册协议")
def reg1():
    return render_template("index/用户注册协议.html")


@login_blu.route("/getpass")
def getpass():
    return render_template("index/getpass.html")


@login_blu.route("/verifyCode")
def verifyCode():
    from app.utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    # print("注册时的验证码为：", name, text, image)  # hash值  验证码值  图片内容

    # 将生成的图片验证码值作为value，存储到session中
    session["captcha"] = text  # 通过session的方式将刚刚生成的图片验证码的值，进行存储，以便在登录的时候进行验证 图片验证码是否输入正确

    # 返回响应内容
    resp = make_response(image)
    # 设置内容类型
    resp.headers['Content-Type'] = 'image/jpg'
    return resp


@login_blu.route('/dologin', methods=['POST'])
def dologin():
    # if session["user"]:
    #     return render_template("")
    # 获取用户注册是提交的数据
    mobile = request.form.get('userinp')
    password = request.form.get('password')
    print(mobile,password)
    # #  测试专用一下
    # ret = {
    #     'errno': "0",
    #     'errmsg': '登录成功'
    # }
    # return jsonify(ret)
    # #  测试专用一上

    # 查询数据库
    if not all([mobile, password]):
        ret = {
            'errno': 3,
            'errmsg': "缺少参数"
        }
        return jsonify(ret)
    user = db.session.query(User).filter(User.mobile == mobile, User.password_hash == password).first()
    print(user)
    if user:
        ret = {
            'errno': 0,
            'errmsg': '登录成功'
        }
        # session["user"] = user
        session['user_id'] = user.id
        session["user_mobile"] = mobile  # 登录成功 session中存储用户的手机号
        return jsonify(ret)
    else:
        ret = {
            'errno': 2,
            'errmsg': '账号或者密码错误'
        }
        return jsonify(ret)

@login_blu.route("/checkdata", methods=["POST"])
def checkdata():
    # print(request.json)
    print(request.form)

    if request.form.get("type") == "phone":
        # print(request.form.get("inp"))
        phone = request.form.get("inp")
        user = db.session.query(User).filter(User.mobile == phone).first()
        if user:
            ret = {
            'code': "0",
            'msg': '密码找回成功'
            }
        else:
            ret = {
                'code': "2",
                'msg': '该手机号未在本网站注册'
            }
        return jsonify(ret)


@login_blu.route("/resetverify", methods=["POST"])
def resetverify():
    """获取手机验证码 手机号 进行验证 跳转的到 重设密码页面"""
    # print(request.form, "asdfasdfasdf")

    moble = request.form.get("inp")
    code = request.form.get("code")
    moble = request.form.get("inp")
    phone_code = session.get("phone_code")
    print("phone_code", phone_code,type(phone_code),code, type(code))

    if code == str(phone_code):
        ret = {
            'code': "0",
            'msg': '密码找回成功'
        }
        user = db.session.query(User).filter(User.mobile == moble).first()
        # current_app.user = user
        # print("g里面存储user",current_app.user)
        # session.user = user
        # print("session里面存储user", session.user)
    else:
        ret = {
            'code': "1",
            'msg': '手机验证码错误'
        }
    return jsonify(ret)


@login_blu.route("/getcode", methods=["POST"])
def getcode():
    type = request.form.get("type")
    if type == "reset":
        # 重置密码 所用
        # print("getcode")
        # 发送验证码
        # print("手机验证码----------------------------------------》")
        # print(request.form)
        phone = request.form.get("phone")  # 获取手机号
        code = request.form.get("code")  # 获取图片验证码
        print(session.get("captcha"))
        if code.lower() == session.get("captcha").lower():
            phone_code = random.randint(10000,100000)  # 生成收据验证码5位数
            session["phone_code"] = phone_code
            print("验证码")
            print("验证码",phone_code)
            send_sms(phone,phone_code)
            ret = {"code":0}
            session["user_mobile"] = phone
        else:
            ret = {"code":2}
        return jsonify(ret)
    elif type == "login":
        print("getcode")
        mobile = request.form.get("phone")
        user = db.session.query(User).filter(User.mobile == mobile).first()
        # if not user:
        #     ret = {"code":"2","msg":"该账户未注册"}
        #     print(ret)
        #     return jsonify(ret)
        # ret = {"code":"0","msg":"已发送验证码"}
        # print(ret)
        # return jsonify(ret)
        phone_code = random.randint(10000, 100000)  # 生成收据验证码5位数
        session["phone_code"] = phone_code
        print("验证码")
        print("验证码", phone_code)
        send_sms(mobile, phone_code)
        ret = {"code": 0}
        return jsonify(ret)



# reset_password
@login_blu.route("/reset_password")
def reset_password():
    return render_template("index/reset_password.html")

# resetpassword
@login_blu.route("/resetpassword", methods=["POST"])
@login_user_data
def resetpassword():
    # print(g)
    user = g.user
    # user = current_app.user
    print(user)
    try:
        if user:
            print("successful")
            print(request.form)
            newpass = request.form.get("newpass")
            repass = request.form.get("repass")
            u = db.session.query(User).filter(User.mobile == user.mobile).first()
            u.password_hash = newpass
            db.session.commit()
            print(u.password_hash, "password")
            ret = {"code":"0", "msg":"修改完成"}
            return jsonify(ret)
        else:
            ret = {"code": "1", "msg": "修改失败"}
            return jsonify(ret)
    except:
        ret = {"code": "1", "msg": "修改失败2"}
        return jsonify(ret)



# ---------------------------------------------------------------------------------以下短信登陆
@login_blu.route("/checkPhone", methods=["POST"])
def checkPhone():
    print("checkPhone")
    print(request.form)
    mobile = request.form.get("phone")
    user = db.session.query(User).filter(User.mobile == mobile).first()
    if not user:
        ret = {
            "code":"1",
            "msg":"此手机号未在注册"
        }
        return jsonify(ret)
    ret = {
        "code": "0",
        "msg": "验证码发送成功"
    }
    return jsonify(ret)

@login_blu.route("/plogin", methods=["POST"])
def plogin():
    print(request.form)
    mobile = request.form.get("phone")
    code = request.form.get("code")
    if not all([mobile,code]):
        ret = {
            'code': "1",
            'msg': '缺少参数'
        }
        print("lose")
        return jsonify(ret)
    if code == str(session.get("phone_code")):
        ret = {
            'code': "0",
            'msg': '登录成功'
        }
        user = db.session.query(User).filter(User.mobile == mobile).first()
        session["user_mobile"] = mobile
        print("success")

        return jsonify(ret)
    else:
        print(session.get("phone_code"), type(session.get("phone_code")))
        print(code, type(code))
        ret = {
            'code': "1",
            'msg': '验证码错误'
        }

        return jsonify(ret)
